{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# PROCESS"
      ],
      "metadata": {
        "id": "RCbtvt33xjGk"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "Agentic system to retrieve financial data about a company:\n",
        "\n",
        "1. Using LlamaIndex\n",
        "\n",
        "2. Using Anthropic : Claude 3.5 sonnet\n",
        "\n",
        "3. Using Financial Modeling Prep API, in which you can\n",
        "provide several information:\n",
        "\n",
        "  * Stock Prices, EPS, PE,...\n",
        "\n",
        "  * Company basic information: Sector, Industry, Market Cap, description, beta,...\n",
        "\n",
        "  * Income statement\n",
        "\n",
        "  You can also fetch from Financial Modeling Prep API:\n",
        "\n",
        "  * Balance Sheet\n",
        "\n",
        "  * Cash Flow\n",
        "\n",
        "  * Key Metrics\n",
        "\n",
        "\n"
      ],
      "metadata": {
        "id": "bSXE5BeJwbyN"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "  Other endpoints are not free:\n",
        "\n",
        "  * News\n",
        "\n",
        "  * News Sentiment\n",
        "\n",
        "  * ...\n",
        "  "
      ],
      "metadata": {
        "id": "qLJ7OODgypm0"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install llama-index-llms-anthropic -q\n",
        "!pip install llama-index -q"
      ],
      "metadata": {
        "id": "D2yu_UJqGpkc"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "from llama_index.llms.anthropic import Anthropic\n",
        "from llama_index.core.tools import FunctionTool\n",
        "\n",
        "import nest_asyncio\n",
        "\n",
        "nest_asyncio.apply()"
      ],
      "metadata": {
        "id": "P-9DTXZ8GwO7"
      },
      "execution_count": 3,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Anthropic LLM and API keys"
      ],
      "metadata": {
        "id": "582ClVVJQwXu"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from google.colab import userdata\n",
        "CLAUDE_API_KEY = userdata.get('CLAUDE_API_KEY')\n",
        "FINANCIAL_MODELING_PREP_API_KEY = userdata.get('FINANCIAL_MODELING_PREP_API_KEY')"
      ],
      "metadata": {
        "id": "3yKlArJOG1mf"
      },
      "execution_count": 12,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "“Data provided by Financial Modeling Prep”\n",
        "\n",
        "https://financialmodelingprep.com/developer/docs/."
      ],
      "metadata": {
        "id": "19jro2CVNTGa"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "llm_anthropic = Anthropic(model=\"claude-3-5-sonnet-20240620\", api_key=CLAUDE_API_KEY)"
      ],
      "metadata": {
        "id": "RIGsosO8Gyls"
      },
      "execution_count": 5,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Tools"
      ],
      "metadata": {
        "id": "9NofAFu7Q3I-"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## get_stock_price"
      ],
      "metadata": {
        "id": "e7wU6iFYQuDW"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "import requests\n",
        "\n",
        "# Define the functions that will fetch financial data\n",
        "def get_stock_price(symbol):\n",
        "    \"\"\"\n",
        "    Fetch the current stock price for the given symbol, the current volume, the average price 50d and 200d, EPS, PE and the next earnings Announcement.\n",
        "    \"\"\"\n",
        "    url = f\"https://financialmodelingprep.com/api/v3/quote-order/{symbol}?apikey={FINANCIAL_MODELING_PREP_API_KEY}\"\n",
        "    response = requests.get(url)\n",
        "    data = response.json()\n",
        "    try:\n",
        "        price = data[0]['price']\n",
        "        volume = data[0]['volume']\n",
        "        priceAvg50 = data[0]['priceAvg50']\n",
        "        priceAvg200 = data[0]['priceAvg200']\n",
        "        eps = data[0]['eps']\n",
        "        pe = data[0]['pe']\n",
        "        earningsAnnouncement = data[0]['earningsAnnouncement']\n",
        "        return {\"symbol\": symbol.upper(), \"price\": price, \"volume\":volume,\"priceAvg50\":priceAvg50, \"priceAvg200\":priceAvg200, \"EPS\":eps, \"PE\":pe, \"earningsAnnouncement\":earningsAnnouncement }\n",
        "    except (IndexError, KeyError):\n",
        "        return {\"error\": f\"Could not fetch price for symbol: {symbol}\"}\n",
        "\n",
        "## DATA PROVIDED BY THIS ENDPOINT:\n",
        "# [{'symbol': 'AAPL',\n",
        "#   'name': 'Apple Inc.',\n",
        "#   'price': 222.5,\n",
        "#   'changesPercentage': -0.1212,\n",
        "#   'change': -0.27,\n",
        "#   'dayLow': 221.91,\n",
        "#   'dayHigh': 224.03,\n",
        "#   'yearHigh': 237.23,\n",
        "#   'yearLow': 164.08,\n",
        "#   'marketCap': 3382912250000,\n",
        "#   'priceAvg50': 223.0692,\n",
        "#   'priceAvg200': 195.382,\n",
        "#   'exchange': 'NASDAQ',\n",
        "#   'volume': 35396922,\n",
        "#   'avgVolume': 57548506,\n",
        "#   'open': 223.58,\n",
        "#   'previousClose': 222.77,\n",
        "#   'eps': 6.57,\n",
        "#   'pe': 33.87,\n",
        "#   'earningsAnnouncement': '2024-10-31T00:00:00.000+0000',\n",
        "#   'sharesOutstanding': 15204100000,\n",
        "#   'timestamp': 1726257601}]\n"
      ],
      "metadata": {
        "id": "dB9dnfMRId28"
      },
      "execution_count": 20,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## get_company_financials"
      ],
      "metadata": {
        "id": "B-Ogv7FjQsZ3"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def get_company_financials(symbol):\n",
        "    \"\"\"\n",
        "    Fetch basic financial information for the given company symbol such as the industry, the sector, the name of the company, and the market capitalization.\n",
        "    \"\"\"\n",
        "    url = f\"https://financialmodelingprep.com/api/v3/profile/{symbol}?apikey={FINANCIAL_MODELING_PREP_API_KEY}\"\n",
        "    response = requests.get(url)\n",
        "    data = response.json()\n",
        "    try:\n",
        "        results = data[0]\n",
        "        financials = {\n",
        "            \"symbol\": results[\"symbol\"],\n",
        "            \"companyName\": results[\"companyName\"],\n",
        "            \"marketCap\": results[\"mktCap\"],\n",
        "            \"industry\": results[\"industry\"],\n",
        "            \"sector\": results[\"sector\"],\n",
        "            \"website\": results[\"website\"],\n",
        "            \"beta\":results[\"beta\"],\n",
        "            \"price\":results[\"price\"],\n",
        "        }\n",
        "        return financials\n",
        "    except (IndexError, KeyError):\n",
        "        return {\"error\": f\"Could not fetch financials for symbol: {symbol}\"}\n",
        "\n",
        "## DATA PROVIDED BY THIS ENDPOINT:\n",
        "# [{'symbol': 'AAPL',\n",
        "#   'price': 222.5,\n",
        "#   'beta': 1.24,\n",
        "#   'volAvg': 57548506,\n",
        "#   'mktCap': 3382912250000,\n",
        "#   'lastDiv': 1,\n",
        "#   'range': '164.08-237.23',\n",
        "#   'changes': -0.27,\n",
        "#   'companyName': 'Apple Inc.',\n",
        "#   'currency': 'USD',\n",
        "#   'cik': '0000320193',\n",
        "#   'isin': 'US0378331005',\n",
        "#   'cusip': '037833100',\n",
        "#   'exchange': 'NASDAQ Global Select',\n",
        "#   'exchangeShortName': 'NASDAQ',\n",
        "#   'industry': 'Consumer Electronics',\n",
        "#   'website': 'https://www.apple.com',\n",
        "#   'description': 'Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide. The company offers iPhone, a line of smartphones; Mac, a line of personal computers; iPad, a line of multi-purpose tablets; and wearables, home, and accessories comprising AirPods, Apple TV, Apple Watch, Beats products, and HomePod. It also provides AppleCare support and cloud services; and operates various platforms, including the App Store that allow customers to discover and download applications and digital content, such as books, music, video, games, and podcasts. In addition, the company offers various services, such as Apple Arcade, a game subscription service; Apple Fitness+, a personalized fitness service; Apple Music, which offers users a curated listening experience with on-demand radio stations; Apple News+, a subscription news and magazine service; Apple TV+, which offers exclusive original content; Apple Card, a co-branded credit card; and Apple Pay, a cashless payment service, as well as licenses its intellectual property. The company serves consumers, and small and mid-sized businesses; and the education, enterprise, and government markets. It distributes third-party applications for its products through the App Store. The company also sells its products through its retail and online stores, and direct sales force; and third-party cellular network carriers, wholesalers, retailers, and resellers. Apple Inc. was incorporated in 1977 and is headquartered in Cupertino, California.',\n",
        "#   'ceo': 'Mr. Timothy D. Cook',\n",
        "#   'sector': 'Technology',\n",
        "#   'country': 'US',\n",
        "#   'fullTimeEmployees': '161000',\n",
        "#   'phone': '408 996 1010',\n",
        "#   'address': 'One Apple Park Way',\n",
        "#   'city': 'Cupertino',\n",
        "#   'state': 'CA',\n",
        "#   'zip': '95014',\n",
        "#   'dcfDiff': 55.70546,\n",
        "#   'dcf': 166.79453554058594,\n",
        "#   'image': 'https://financialmodelingprep.com/image-stock/AAPL.png',\n",
        "#   'ipoDate': '1980-12-12',\n",
        "#   'defaultImage': False,\n",
        "#   'isEtf': False,\n",
        "#   'isActivelyTrading': True,\n",
        "#   'isAdr': False,\n",
        "#   'isFund': False}]"
      ],
      "metadata": {
        "id": "ZybkTXSFKXuq"
      },
      "execution_count": 25,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## get_income_statement"
      ],
      "metadata": {
        "id": "T3J_JctYQpWO"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def get_income_statement(symbol):\n",
        "    \"\"\"\n",
        "    Fetch last income statement for the given company symbol such as revenue, gross profit, net income, EBITDA, EPS.\n",
        "    \"\"\"\n",
        "    url = f\"https://financialmodelingprep.com/api/v3/income-statement/{symbol}?period=annual&apikey={FINANCIAL_MODELING_PREP_API_KEY}\"\n",
        "    response = requests.get(url)\n",
        "    data = response.json()\n",
        "    try:\n",
        "        results = data[0]\n",
        "        financials = {\n",
        "            \"date\": results[\"date\"],\n",
        "            \"revenue\": results[\"revenue\"],\n",
        "            \"gross profit\": results[\"grossProfit\"],\n",
        "            \"net Income\": results[\"netIncome\"],\n",
        "            \"ebitda\": results[\"ebitda\"],\n",
        "            \"EPS\": results[\"eps\"],\n",
        "            \"EPS diluted\":results[\"epsdiluted\"]\n",
        "        }\n",
        "        return data, financials\n",
        "    except (IndexError, KeyError):\n",
        "        return {\"error\": f\"Could not fetch financials for symbol: {symbol}\"}\n",
        "\n",
        "## DATA PROVIDED BY THIS ENDPOINT:\n",
        "# {'date': '2023-09-30',\n",
        "#   'symbol': 'AAPL',\n",
        "#   'reportedCurrency': 'USD',\n",
        "#   'cik': '0000320193',\n",
        "#   'fillingDate': '2023-11-03',\n",
        "#   'acceptedDate': '2023-11-02 18:08:27',\n",
        "#   'calendarYear': '2023',\n",
        "#   'period': 'FY',\n",
        "#   'revenue': 383285000000,\n",
        "#   'costOfRevenue': 214137000000,\n",
        "#   'grossProfit': 169148000000,\n",
        "#   'grossProfitRatio': 0.4413112958,\n",
        "#   'researchAndDevelopmentExpenses': 29915000000,\n",
        "#   'generalAndAdministrativeExpenses': 0,\n",
        "#   'sellingAndMarketingExpenses': 0,\n",
        "#   'sellingGeneralAndAdministrativeExpenses': 24932000000,\n",
        "#   'otherExpenses': 382000000,\n",
        "#   'operatingExpenses': 55229000000,\n",
        "#   'costAndExpenses': 269366000000,\n",
        "#   'interestIncome': 3750000000,\n",
        "#   'interestExpense': 3933000000,\n",
        "#   'depreciationAndAmortization': 11519000000,\n",
        "#   'ebitda': 125820000000,\n",
        "#   'ebitdaratio': 0.3282674772,\n",
        "#   'operatingIncome': 114301000000,\n",
        "#   'operatingIncomeRatio': 0.2982141227,\n",
        "#   'totalOtherIncomeExpensesNet': -565000000,\n",
        "#   'incomeBeforeTax': 113736000000,\n",
        "#   'incomeBeforeTaxRatio': 0.2967400237,\n",
        "#   'incomeTaxExpense': 16741000000,\n",
        "#   'netIncome': 96995000000,\n",
        "#   'netIncomeRatio': 0.2530623426,\n",
        "#   'eps': 6.16,\n",
        "#   'epsdiluted': 6.13,\n",
        "#   'weightedAverageShsOut': 15744231000,\n",
        "#   'weightedAverageShsOutDil': 15812547000,\n",
        "#   'link': 'https://www.sec.gov/Archives/edgar/data/320193/000032019323000106/0000320193-23-000106-index.htm',\n",
        "#   'finalLink': 'https://www.sec.gov/Archives/edgar/data/320193/000032019323000106/aapl-20230930.htm'}\n",
        "\n"
      ],
      "metadata": {
        "id": "k4Cp4AALOWmn"
      },
      "execution_count": 29,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Tools"
      ],
      "metadata": {
        "id": "cSLBoVqQzwI8"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# get_stock_price, get_company_financials, get_income_statement"
      ],
      "metadata": {
        "id": "SQn6Ft2LQQje"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Anthropic Agent"
      ],
      "metadata": {
        "id": "Iu-qsEbuQ9Nd"
      }
    },
    {
      "cell_type": "markdown",
      "source": [],
      "metadata": {
        "id": "TyM0DguC0R1x"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Convert the functions to tools function"
      ],
      "metadata": {
        "id": "365UNtjwz1p7"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "tool_stock_price = FunctionTool.from_defaults(fn=get_stock_price)\n",
        "tool_company_financials = FunctionTool.from_defaults(fn=get_company_financials)\n",
        "tool_income_statement = FunctionTool.from_defaults(fn=get_income_statement)"
      ],
      "metadata": {
        "id": "Ki9i5Z2mQcq2"
      },
      "execution_count": 34,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Create Anthropic Agent by incorporating the predefined tools:"
      ],
      "metadata": {
        "id": "9OK6CGIdz6Cy"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from llama_index.core.agent import FunctionCallingAgent\n",
        "\n",
        "agent = FunctionCallingAgent.from_tools(\n",
        "    [tool_stock_price, tool_company_financials, tool_income_statement],\n",
        "    llm=llm_anthropic,\n",
        "    verbose=True,\n",
        "    allow_parallel_tool_calls=False,\n",
        ")"
      ],
      "metadata": {
        "id": "RJf2THCBRBZN"
      },
      "execution_count": 36,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Start Chatting"
      ],
      "metadata": {
        "id": "8jazhyXv0FMS"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "query= \"Give me the current price of Apple\"\n",
        "response = agent.chat(query)\n",
        "print(str(response))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "J5Q67w8bRJ3-",
        "outputId": "17591849-ff6e-432f-cbba-0b9dbc72af97"
      },
      "execution_count": 37,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "> Running step 9e728b09-a255-4819-9a94-842749e7cfd4. Step input: Give me the current price of Apple\n",
            "Added user message to memory: Give me the current price of Apple\n",
            "=== LLM Response ===\n",
            "Certainly! I'll fetch the current stock price for Apple using the get_stock_price function. Apple's stock symbol is AAPL, so I'll use that for the query.\n",
            "=== Calling Function ===\n",
            "Calling function: get_stock_price with args: {\"symbol\": \"AAPL\"}\n",
            "=== Function Output ===\n",
            "{'symbol': 'AAPL', 'price': 222.5, 'volume': 35396922, 'priceAvg50': 223.0692, 'priceAvg200': 195.382, 'EPS': 6.57, 'PE': 33.87, 'earningsAnnouncement': '2024-10-31T00:00:00.000+0000'}\n",
            "> Running step e99a2ccd-87dc-4285-aecf-aba2c509c8bb. Step input: None\n",
            "=== LLM Response ===\n",
            "Based on the information retrieved, here's the current stock information for Apple (AAPL):\n",
            "\n",
            "1. Current Price: $222.50\n",
            "2. Trading Volume: 35,396,922 shares\n",
            "3. Earnings Per Share (EPS): $6.57\n",
            "4. Price-to-Earnings Ratio (P/E): 33.87\n",
            "5. Next Earnings Announcement: October 31, 2024\n",
            "\n",
            "Additionally, some other interesting data points:\n",
            "- 50-day Moving Average: $223.07\n",
            "- 200-day Moving Average: $195.38\n",
            "\n",
            "The stock is currently trading slightly below its 50-day moving average but well above its 200-day moving average, which could indicate a generally positive trend over the longer term.\n",
            "\n",
            "Is there any other information about Apple's stock or financials you'd like to know?\n",
            "Based on the information retrieved, here's the current stock information for Apple (AAPL):\n",
            "\n",
            "1. Current Price: $222.50\n",
            "2. Trading Volume: 35,396,922 shares\n",
            "3. Earnings Per Share (EPS): $6.57\n",
            "4. Price-to-Earnings Ratio (P/E): 33.87\n",
            "5. Next Earnings Announcement: October 31, 2024\n",
            "\n",
            "Additionally, some other interesting data points:\n",
            "- 50-day Moving Average: $223.07\n",
            "- 200-day Moving Average: $195.38\n",
            "\n",
            "The stock is currently trading slightly below its 50-day moving average but well above its 200-day moving average, which could indicate a generally positive trend over the longer term.\n",
            "\n",
            "Is there any other information about Apple's stock or financials you'd like to know?\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "query= \"What was the last revenue reported by Apple?\"\n",
        "response = agent.chat(query)\n",
        "# print(str(response))"
      ],
      "metadata": {
        "id": "MapCDAgnRnkt"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "print(str(response))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "geRlMk8ISPQ1",
        "outputId": "e747ecd9-d9f7-4612-e3dc-5c9df5ffcd2c"
      },
      "execution_count": 42,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Thank you for your patience. I've retrieved the income statement information for Apple (AAPL). Based on the most recent data available, here's the information about Apple's last reported revenue:\n",
            "\n",
            "1. Date of Report: September 30, 2023\n",
            "2. Last Reported Revenue: $383,285,000,000 (383.285 billion USD)\n",
            "\n",
            "This revenue figure is for Apple's 2023 fiscal year, which ended on September 30, 2023. \n",
            "\n",
            "Some additional financial highlights from this report:\n",
            "\n",
            "1. Gross Profit: $169,148,000,000 (169.148 billion USD)\n",
            "2. Net Income: $96,995,000,000 (96.995 billion USD)\n",
            "3. EBITDA (Earnings Before Interest, Taxes, Depreciation, and Amortization): $125,820,000,000 (125.82 billion USD)\n",
            "4. Earnings Per Share (EPS): $6.16\n",
            "5. Diluted Earnings Per Share: $6.13\n",
            "\n",
            "It's worth noting that Apple's revenue for the fiscal year 2023 showed a slight decrease compared to the previous fiscal year (2022), which had a revenue of $394,328,000,000 (394.328 billion USD).\n",
            "\n",
            "Is there any specific aspect of Apple's financial performance you'd like to know more about?\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# ChatBot using Anthropic Agent:"
      ],
      "metadata": {
        "id": "V9-c6pkYTeK9"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "while True:\n",
        "  user_input = input(\"\\nYou: \")\n",
        "  if user_input.lower() in [\"exit\", \"quit\"]:\n",
        "    print(\"Assistant: Goodbye!\")\n",
        "    break\n",
        "\n",
        "  response = agent.chat(user_input)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "zDt950-MSZj1",
        "outputId": "4bb8b3a6-6250-473a-d164-07ec52ed3582"
      },
      "execution_count": 45,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "You: What is the current price of Amazon?\n",
            "> Running step 5f42daee-1bf4-42d6-9f75-c7ef36145624. Step input: What is the current price of Amazon?\n",
            "Added user message to memory: What is the current price of Amazon?\n",
            "=== LLM Response ===\n",
            "Certainly! I'll fetch the current stock price for Amazon using the get_stock_price function. Amazon's stock symbol is AMZN, so I'll use that for the query.\n",
            "=== Calling Function ===\n",
            "Calling function: get_stock_price with args: {\"symbol\": \"AMZN\"}\n",
            "=== Function Output ===\n",
            "{'symbol': 'AMZN', 'price': 186.49, 'volume': 25995878, 'priceAvg50': 180.1618, 'priceAvg200': 173.72334, 'EPS': 4.19, 'PE': 44.51, 'earningsAnnouncement': '2024-10-24T00:00:00.000+0000'}\n",
            "> Running step aff99084-334e-46de-b46f-7362d29e2d24. Step input: None\n",
            "=== LLM Response ===\n",
            "Based on the information retrieved, here's the current stock information for Amazon (AMZN):\n",
            "\n",
            "1. Current Price: $186.49\n",
            "2. Trading Volume: 25,995,878 shares\n",
            "3. Earnings Per Share (EPS): $4.19\n",
            "4. Price-to-Earnings Ratio (P/E): 44.51\n",
            "5. Next Earnings Announcement: October 24, 2024\n",
            "\n",
            "Additionally, some other interesting data points:\n",
            "- 50-day Moving Average: $180.16\n",
            "- 200-day Moving Average: $173.72\n",
            "\n",
            "The stock is currently trading above both its 50-day and 200-day moving averages, which could indicate a positive trend.\n",
            "\n",
            "Is there any other information about Amazon's stock or financials you'd like to know?\n",
            "\n",
            "You: what is the last reported revenue?\n",
            "> Running step e1398244-a302-4941-aa8b-f90345daa785. Step input: what is the last reported revenue?\n",
            "Added user message to memory: what is the last reported revenue?\n",
            "=== LLM Response ===\n",
            "To get the last reported revenue for Amazon, I'll need to fetch their most recent income statement. I'll use the get_income_statement function to retrieve this information.\n",
            "=== Calling Function ===\n",
            "Calling function: get_income_statement with args: {\"symbol\": \"AMZN\"}\n",
            "=== Function Output ===\n",
            "([{'date': '2023-12-31', 'symbol': 'AMZN', 'reportedCurrency': 'USD', 'cik': '0001018724', 'fillingDate': '2024-02-02', 'acceptedDate': '2024-02-01 18:48:30', 'calendarYear': '2023', 'period': 'FY', 'revenue': 574785000000, 'costOfRevenue': 304739000000, 'grossProfit': 270046000000, 'grossProfitRatio': 0.4698208896, 'researchAndDevelopmentExpenses': 85622000000, 'generalAndAdministrativeExpenses': 11816000000, 'sellingAndMarketingExpenses': 44370000000, 'sellingGeneralAndAdministrativeExpenses': 146805000000, 'otherExpenses': -177000000, 'operatingExpenses': 232427000000, 'costAndExpenses': 537933000000, 'interestIncome': 2949000000, 'interestExpense': 3182000000, 'depreciationAndAmortization': 48663000000, 'ebitda': 85515000000, 'ebitdaratio': 0.1487773689, 'operatingIncome': 36852000000, 'operatingIncomeRatio': 0.064114408, 'totalOtherIncomeExpensesNet': 693000000, 'incomeBeforeTax': 37545000000, 'incomeBeforeTaxRatio': 0.0653200762, 'incomeTaxExpense': 7120000000, 'netIncome': 30425000000, 'netIncomeRatio': 0.0529328358, 'eps': 2.95, 'epsdiluted': 2.9, 'weightedAverageShsOut': 10304000000, 'weightedAverageShsOutDil': 10492000000, 'link': 'https://www.sec.gov/Archives/edgar/data/1018724/000101872424000008/0001018724-24-000008-index.htm', 'finalLink': 'https://www.sec.gov/Archives/edgar/data/1018724/000101872424000008/amzn-20231231.htm'}, {'date': '2022-12-31', 'symbol': 'AMZN', 'reportedCurrency': 'USD', 'cik': '0001018724', 'fillingDate': '2023-02-03', 'acceptedDate': '2023-02-02 18:27:34', 'calendarYear': '2022', 'period': 'FY', 'revenue': 513983000000, 'costOfRevenue': 288831000000, 'grossProfit': 225152000000, 'grossProfitRatio': 0.4380533987, 'researchAndDevelopmentExpenses': 73213000000, 'generalAndAdministrativeExpenses': 11891000000, 'sellingAndMarketingExpenses': 42238000000, 'sellingGeneralAndAdministrativeExpenses': 138428000000, 'otherExpenses': -16806000000, 'operatingExpenses': 229713000000, 'costAndExpenses': 518544000000, 'interestIncome': 989000000, 'interestExpense': 2367000000, 'depreciationAndAmortization': 41921000000, 'ebitda': 54618000000, 'ebitdaratio': 0.106264215, 'operatingIncome': 12248000000, 'operatingIncomeRatio': 0.0238295819, 'totalOtherIncomeExpensesNet': -16806000000, 'incomeBeforeTax': -5936000000, 'incomeBeforeTaxRatio': -0.0115490201, 'incomeTaxExpense': -3217000000, 'netIncome': -2722000000, 'netIncomeRatio': -0.005295895, 'eps': -0.27, 'epsdiluted': -0.27, 'weightedAverageShsOut': 10189000000, 'weightedAverageShsOutDil': 10189000000, 'link': 'https://www.sec.gov/Archives/edgar/data/1018724/000101872423000004/0001018724-23-000004-index.htm', 'finalLink': 'https://www.sec.gov/Archives/edgar/data/1018724/000101872423000004/amzn-20221231.htm'}, {'date': '2021-12-31', 'symbol': 'AMZN', 'reportedCurrency': 'USD', 'cik': '0001018724', 'fillingDate': '2022-02-04', 'acceptedDate': '2022-02-03 18:46:51', 'calendarYear': '2021', 'period': 'FY', 'revenue': 469822000000, 'costOfRevenue': 272344000000, 'grossProfit': 197478000000, 'grossProfitRatio': 0.4203251444, 'researchAndDevelopmentExpenses': 56052000000, 'generalAndAdministrativeExpenses': 8823000000, 'sellingAndMarketingExpenses': 32551000000, 'sellingGeneralAndAdministrativeExpenses': 116485000000, 'otherExpenses': 14633000000, 'operatingExpenses': 157962000000, 'costAndExpenses': 430306000000, 'interestIncome': 448000000, 'interestExpense': 1809000000, 'depreciationAndAmortization': 34296000000, 'ebitda': 59741000000, 'ebitdaratio': 0.1271566678, 'operatingIncome': 24879000000, 'operatingIncomeRatio': 0.0529540975, 'totalOtherIncomeExpensesNet': 13276000000, 'incomeBeforeTax': 38155000000, 'incomeBeforeTaxRatio': 0.0812116078, 'incomeTaxExpense': 4791000000, 'netIncome': 33364000000, 'netIncomeRatio': 0.0710141288, 'eps': 3.3, 'epsdiluted': 3.24, 'weightedAverageShsOut': 10120000000, 'weightedAverageShsOutDil': 10300000000, 'link': 'https://www.sec.gov/Archives/edgar/data/1018724/000101872422000005/0001018724-22-000005-index.htm', 'finalLink': 'https://www.sec.gov/Archives/edgar/data/1018724/000101872422000005/amzn-20211231.htm'}, {'date': '2020-12-31', 'symbol': 'AMZN', 'reportedCurrency': 'USD', 'cik': '0001018724', 'fillingDate': '2021-02-03', 'acceptedDate': '2021-02-02 19:44:10', 'calendarYear': '2020', 'period': 'FY', 'revenue': 386064000000, 'costOfRevenue': 233307000000, 'grossProfit': 152757000000, 'grossProfitRatio': 0.3956779187, 'researchAndDevelopmentExpenses': 42740000000, 'generalAndAdministrativeExpenses': 6668000000, 'sellingAndMarketingExpenses': 22008000000, 'sellingGeneralAndAdministrativeExpenses': 87193000000, 'otherExpenses': 2371000000, 'operatingExpenses': 127471000000, 'costAndExpenses': 360778000000, 'interestIncome': 555000000, 'interestExpense': 1647000000, 'depreciationAndAmortization': 25251000000, 'ebitda': 48647000000, 'ebitdaratio': 0.126007605, 'operatingIncome': 22899000000, 'operatingIncomeRatio': 0.0593139998, 'totalOtherIncomeExpensesNet': 1295000000, 'incomeBeforeTax': 24194000000, 'incomeBeforeTaxRatio': 0.0626683659, 'incomeTaxExpense': 2863000000, 'netIncome': 21331000000, 'netIncomeRatio': 0.055252497, 'eps': 2.13, 'epsdiluted': 2.09, 'weightedAverageShsOut': 10000000000, 'weightedAverageShsOutDil': 10200000000, 'link': 'https://www.sec.gov/Archives/edgar/data/1018724/000101872421000004/0001018724-21-000004-index.htm', 'finalLink': 'https://www.sec.gov/Archives/edgar/data/1018724/000101872421000004/amzn-20201231.htm'}, {'date': '2019-12-31', 'symbol': 'AMZN', 'reportedCurrency': 'USD', 'cik': '0001018724', 'fillingDate': '2020-01-31', 'acceptedDate': '2020-01-30 20:46:13', 'calendarYear': '2019', 'period': 'FY', 'revenue': 280522000000, 'costOfRevenue': 165536000000, 'grossProfit': 114986000000, 'grossProfitRatio': 0.4099001148, 'researchAndDevelopmentExpenses': 35931000000, 'generalAndAdministrativeExpenses': 5203000000, 'sellingAndMarketingExpenses': 18878000000, 'sellingGeneralAndAdministrativeExpenses': 64313000000, 'otherExpenses': 203000000, 'operatingExpenses': 100256000000, 'costAndExpenses': 265792000000, 'interestIncome': 832000000, 'interestExpense': 1600000000, 'depreciationAndAmortization': 21789000000, 'ebitda': 37039000000, 'ebitdaratio': 0.13203599, 'operatingIncome': 14541000000, 'operatingIncomeRatio': 0.0518355067, 'totalOtherIncomeExpensesNet': -579000000, 'incomeBeforeTax': 13962000000, 'incomeBeforeTaxRatio': 0.0497714974, 'incomeTaxExpense': 2374000000, 'netIncome': 11588000000, 'netIncomeRatio': 0.0413087031, 'eps': 1.17, 'epsdiluted': 1.15, 'weightedAverageShsOut': 9880000000, 'weightedAverageShsOutDil': 10080000000, 'link': 'https://www.sec.gov/Archives/edgar/data/1018724/000101872420000004/0001018724-20-000004-index.htm', 'finalLink': 'https://www.sec.gov/Archives/edgar/data/1018724/000101872420000004/amzn-20191231x10k.htm'}], {'date': '2023-12-31', 'revenue': 574785000000, 'gross profit': 270046000000, 'net Income': 30425000000, 'ebitda': 85515000000, 'EPS': 2.95, 'EPS diluted': 2.9})\n",
            "> Running step 73b2850a-0fdd-47d8-99e3-90597cc2a1e5. Step input: None\n",
            "=== LLM Response ===\n",
            "Thank you for your patience. I've retrieved the income statement information for Amazon (AMZN). Based on the most recent data available, here's the information about Amazon's last reported revenue:\n",
            "\n",
            "The last reported revenue for Amazon was $574,785,000,000 (574.785 billion USD) for the fiscal year ending December 31, 2023.\n",
            "\n",
            "This figure represents Amazon's total revenue for their 2023 fiscal year, which is the most recent annual report available based on the data provided.\n",
            "\n",
            "Some additional financial highlights from this report:\n",
            "\n",
            "1. Gross Profit: $270,046,000,000 (270.046 billion USD)\n",
            "2. Net Income: $30,425,000,000 (30.425 billion USD)\n",
            "3. EBITDA (Earnings Before Interest, Taxes, Depreciation, and Amortization): $85,515,000,000 (85.515 billion USD)\n",
            "4. Earnings Per Share (EPS): $2.95\n",
            "5. Diluted Earnings Per Share: $2.90\n",
            "\n",
            "It's worth noting that Amazon's revenue for the fiscal year 2023 showed a significant increase compared to the previous fiscal year (2022), which had a revenue of $513,983,000,000 (513.983 billion USD).\n",
            "\n",
            "Is there any specific aspect of Amazon's financial performance you'd like to know more about?\n",
            "\n",
            "You: What is the beta of Amazon?\n",
            "> Running step d4a674f2-7dce-439a-b079-be5f26b3ebf3. Step input: What is the beta of Amazon?\n",
            "Added user message to memory: What is the beta of Amazon?\n",
            "=== LLM Response ===\n",
            "I apologize, but I don't have a specific function to directly retrieve the beta value for Amazon's stock. The beta is a measure of a stock's volatility in relation to the overall market, and it's not included in the basic stock price or financial statement data we've retrieved so far.\n",
            "\n",
            "To get Amazon's beta, we would need a function that provides more detailed stock metrics or risk measures. Since we don't have such a function available, I can't provide you with the exact current beta value for Amazon.\n",
            "\n",
            "However, I can offer some general information about beta:\n",
            "\n",
            "1. A beta of 1.0 indicates that the stock's price moves with the market.\n",
            "2. A beta greater than 1.0 indicates that the stock is more volatile than the market.\n",
            "3. A beta between 0 and 1.0 indicates that the stock is less volatile than the market.\n",
            "4. A negative beta is rare and would indicate an inverse relation to the market.\n",
            "\n",
            "Typically, large tech companies like Amazon often have betas slightly above 1, indicating they're somewhat more volatile than the overall market. But without access to current data, I can't confirm the exact value.\n",
            "\n",
            "If you need the current beta for Amazon, you might want to check financial websites or stock analysis platforms that provide this information. These values are usually updated regularly and can change over time based on market conditions and the company's performance.\n",
            "\n",
            "Is there any other information about Amazon that I can help you with using the data we have available?\n",
            "\n",
            "You: what is the sector of Amazon?\n",
            "> Running step 0020676c-2203-41c2-b079-284e00e2f3e5. Step input: what is the sector of Amazon?\n",
            "Added user message to memory: what is the sector of Amazon?\n",
            "=== LLM Response ===\n",
            "To get the sector information for Amazon, we can use the get_company_financials function. This function should provide us with basic financial information about the company, including its sector. Let's fetch this information for Amazon.\n",
            "=== Calling Function ===\n",
            "Calling function: get_company_financials with args: {\"symbol\": \"AMZN\"}\n",
            "=== Function Output ===\n",
            "{'symbol': 'AMZN', 'companyName': 'Amazon.com, Inc.', 'marketCap': 1957324444000, 'industry': 'Specialty Retail', 'sector': 'Consumer Cyclical', 'website': 'https://www.amazon.com', 'beta': 1.146, 'price': 186.49}\n",
            "> Running step 86d8022c-90b1-4106-94aa-a9c1521a30e9. Step input: None\n",
            "=== LLM Response ===\n",
            "Thank you for your patience. I've retrieved the company financial information for Amazon (AMZN). Based on this data, I can now answer your question about Amazon's sector and provide some additional relevant information:\n",
            "\n",
            "1. Sector: Consumer Cyclical\n",
            "\n",
            "This means Amazon is classified in the Consumer Cyclical sector, which includes companies that tend to be more sensitive to economic cycles. These businesses typically produce or sell discretionary items and services that consumers may buy more of during an economic expansion and less of during a recession.\n",
            "\n",
            "Additional relevant information from this data:\n",
            "\n",
            "2. Industry: Specialty Retail\n",
            "3. Company Name: Amazon.com, Inc.\n",
            "4. Market Capitalization: $1,957,324,444,000 (approximately 1.96 trillion USD)\n",
            "5. Website: https://www.amazon.com\n",
            "6. Beta: 1.146\n",
            "\n",
            "Interestingly, this function also provided the beta value, which we couldn't retrieve earlier. With a beta of 1.146, Amazon's stock is slightly more volatile than the overall market, which aligns with what we might expect for a large tech company in the Consumer Cyclical sector.\n",
            "\n",
            "Is there anything else you'd like to know about Amazon's classification or financial metrics?\n",
            "\n",
            "You: exit\n",
            "Assistant: Goodbye!\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Key Takeaways:\n",
        "## Interesting results:\n",
        "1.    The agent provides the answer to the requested information, but also make a comparison with the last year, to provide more insightfull analysis.\n",
        "```\n",
        "\"\"\"It's worth noting that Amazon's revenue for the fiscal year 2023 showed a significant increase compared to the previous fiscal year (2022),\n",
        "which had a revenue of $513,983,000,000 (513.983 billion USD).\"\"\"\n",
        "```\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "2.   Beta value: I didn't provide explicit function to fetch the beta value:\n",
        "- I asked first to get the beta value:\n",
        "```\n",
        "\"\"\"I apologize, but I don't have a specific function to directly retrieve the beta value for Amazon's stock. \"\"\"\n",
        "```\n",
        "* However it gives interesting analysis on what does mean beta and what could be the beta for tech companies like Amazon.\n",
        "\n",
        "* I asked another information that calls a function in which the beta is retrieved.\n",
        "-  So it did answer to my question and provide additional information about the beta, because it remembers that it cannot answer it explicitly in the previous request.\n",
        "\n",
        "\n",
        "```\n",
        "\"\"\"Interestingly, this function also provided the beta value, which we couldn't retrieve earlier. With a beta of 1.146, Amazon's stock is slightly more volatile than the overall market, which aligns with what we might expect for a large tech company in the Consumer Cyclical sector.\"\"\"\n",
        "```\n",
        "\n"
      ],
      "metadata": {
        "id": "tA1EnYh8uXm1"
      }
    }
  ]
}